import 'package:mobx/mobx.dart';
import 'package:thal/backstage/blueprint/badge_print.dart';

part 'badge_room.g.dart';

/// 徽章状态管理
class BadgeRoom = _BadgeRoom with _$BadgeRoom;

abstract class _BadgeRoom with Store {
  /// 所有徽章列表
  @observable
  ObservableList<BadgePrint> badges = ObservableList<BadgePrint>();

  /// 用户徽章列表
  @observable
  ObservableList<UserBadgePrint> userBadges = ObservableList<UserBadgePrint>();

  /// 用户当前展示的勋章ID（key: userId, value: badgeId）
  @observable
  ObservableMap<String, String> userDisplayedBadge =
      ObservableMap<String, String>();

  /// 初始化默认徽章数据
  @action
  void initializeDefaultBadges() {
    badges = ObservableList<BadgePrint>.of([
      BadgePrint(
        id: '1',
        name: 'Lake Baikal',
        imageUrl: 'assets/images/badge1.png',
        createdAt: DateTime.now().subtract(const Duration(days: 30)),
      ),
      BadgePrint(
        id: '2',
        name: 'Lake Bled',
        imageUrl: 'assets/images/badge2.png',
        createdAt: DateTime.now().subtract(const Duration(days: 25)),
      ),
      BadgePrint(
        id: '3',
        name: 'Lake Como',
        imageUrl: 'assets/images/badge3.png',
        createdAt: DateTime.now().subtract(const Duration(days: 20)),
      ),
      BadgePrint(
        id: '4',
        name: 'Jade Lake',
        imageUrl: 'assets/images/badge4.png',
        createdAt: DateTime.now().subtract(const Duration(days: 15)),
      ),
      BadgePrint(
        id: '5',
        name: 'Mono Lake',
        imageUrl: 'assets/images/badge5.png',
        createdAt: DateTime.now().subtract(const Duration(days: 10)),
      ),
      BadgePrint(
        id: '6',
        name: 'Lake Matheson',
        imageUrl: 'assets/images/badge6.png',
        createdAt: DateTime.now().subtract(const Duration(days: 5)),
      ),
    ]);

    // 初始化用户徽章数据
    userBadges = ObservableList<UserBadgePrint>.of([
      // admin用户默认获得Lake Explorer徽章
      UserBadgePrint(
        id: '1',
        userId: '1', // admin用户
        badgeId: '1', // Lake Explorer徽章
        earnedAt: DateTime.now().subtract(const Duration(days: 1)),
        isDisplayed: true,
      ),
    ]);
  }

  /// 获取所有徽章
  List<BadgePrint> fetchAllBadges() {
    return List.from(badges);
  }

  /// 根据ID获取徽章
  BadgePrint? fetchBadgeById(String id) {
    try {
      return badges.firstWhere((badge) => badge.id == id);
    } catch (e) {
      return null;
    }
  }

  /// 获取用户的所有徽章
  List<UserBadgePrint> fetchUserBadges(String userId) {
    return userBadges.where((userBadge) => userBadge.userId == userId).toList();
  }

  /// 获取用户展示的徽章
  List<UserBadgePrint> fetchUserDisplayedBadges(String userId) {
    return userBadges
        .where(
          (userBadge) => userBadge.userId == userId && userBadge.isDisplayed,
        )
        .toList();
  }

  /// 检查用户是否拥有某个徽章
  bool hasBadge(String userId, String badgeId) {
    return userBadges.any(
      (userBadge) => userBadge.userId == userId && userBadge.badgeId == badgeId,
    );
  }

  /// 授予用户徽章
  @action
  bool awardBadge(String userId, String badgeId) {
    try {
      // 检查用户是否已经拥有这个徽章
      if (hasBadge(userId, badgeId)) {
        return false; // 已经拥有，不重复授予
      }

      final newUserBadge = UserBadgePrint(
        id: '${DateTime.now().millisecondsSinceEpoch}',
        userId: userId,
        badgeId: badgeId,
        earnedAt: DateTime.now(),
        isDisplayed: true, // 默认展示
      );

      userBadges.add(newUserBadge);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 切换徽章展示状态
  @action
  bool toggleBadgeDisplay(String userId, String badgeId) {
    try {
      final index = userBadges.indexWhere(
        (userBadge) =>
            userBadge.userId == userId && userBadge.badgeId == badgeId,
      );

      if (index != -1) {
        final userBadge = userBadges[index];
        final updatedUserBadge = UserBadgePrint(
          id: userBadge.id,
          userId: userBadge.userId,
          badgeId: userBadge.badgeId,
          earnedAt: userBadge.earnedAt,
          isDisplayed: !userBadge.isDisplayed,
        );

        userBadges[index] = updatedUserBadge;
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  /// 获取用户徽章总数
  int getUserBadgeCount(String userId) {
    return userBadges.where((userBadge) => userBadge.userId == userId).length;
  }

  /// 获取用户展示的徽章数量
  int getUserDisplayedBadgeCount(String userId) {
    return userBadges
        .where(
          (userBadge) => userBadge.userId == userId && userBadge.isDisplayed,
        )
        .length;
  }

  /// 获取徽章详细信息（包含用户是否拥有）
  Map<String, dynamic> getBadgeWithUserStatus(String badgeId, String userId) {
    final badge = fetchBadgeById(badgeId);
    if (badge == null) return {};

    final userBadge = userBadges.firstWhere(
      (ub) => ub.userId == userId && ub.badgeId == badgeId,
      orElse:
          () => UserBadgePrint(
            id: '',
            userId: '',
            badgeId: '',
            earnedAt: DateTime.now(),
            isDisplayed: false,
          ),
    );

    return {
      'badge': badge,
      'hasBadge': hasBadge(userId, badgeId),
      'isDisplayed': userBadge.isDisplayed,
      'earnedAt': userBadge.earnedAt,
    };
  }

  /// 添加新徽章
  @action
  bool addBadge({required String name, required String imageUrl}) {
    try {
      final newBadge = BadgePrint(
        id: (badges.length + 1).toString(),
        name: name,
        imageUrl: imageUrl,
        createdAt: DateTime.now(),
      );
      badges.add(newBadge);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 删除徽章
  @action
  bool removeBadge(String badgeId) {
    try {
      badges.removeWhere((badge) => badge.id == badgeId);
      userBadges.removeWhere((userBadge) => userBadge.badgeId == badgeId);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 设置用户当前展示的勋章
  @action
  void setUserDisplayedBadge(String userId, String badgeId) {
    // 检查用户是否拥有该勋章
    if (hasBadge(userId, badgeId)) {
      userDisplayedBadge[userId] = badgeId;
    }
  }

  /// 获取用户当前展示的勋章ID
  String? getUserDisplayedBadgeId(String userId) {
    return userDisplayedBadge[userId];
  }

  /// 获取用户当前展示的勋章详情
  BadgePrint? getUserDisplayedBadge(String userId) {
    final badgeId = userDisplayedBadge[userId];
    if (badgeId == null) return null;
    return fetchBadgeById(badgeId);
  }

  /// 取消用户展示的勋章
  @action
  void clearUserDisplayedBadge(String userId) {
    userDisplayedBadge.remove(userId);
  }
}
